package ctu.edu.vn.musicmanager.business;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

public class Downloader extends SwingWorker<Void, Void> {
	// Var downloadFile
	public HttpURLConnection httpConn;
	public InputStream inputStream;
	public FileOutputStream outputStream;
	public String fileName; //Tên file
	public int contentLength;
	// Var downloadTask
	public static final int BUFFER_SIZE = 4096;
	public String downloadURL; //Đường dẫn download file
	public String saveDirectory; //Đường dẫn lưu file
	public boolean success, finish;
	public void setDownloadURL(String url) {
		this.downloadURL = url;
	}

	public void setSaveDirectory(String dir) {
		this.saveDirectory = dir;
	}

	public boolean downloadFile(String fileURL) {
		finish = false;
		try {
			URL url = new URL(fileURL);
			httpConn = (HttpURLConnection) url.openConnection();
			int responseCode = httpConn.getResponseCode();

			// always check HTTP response code first
			if (responseCode == HttpURLConnection.HTTP_OK) {
				String disposition = httpConn
						.getHeaderField("Content-Disposition");
				String contentType = httpConn.getContentType();
				contentLength = httpConn.getContentLength();
				// File name là tên bài hát
				if (disposition != null) {
					// extracts file name from header field
					int index = disposition.indexOf("filename=");
					if (index > 0) {
						fileName = disposition.substring(index + 10,
								disposition.length() - 1);
					}
				} else {
					// extracts file name from URL
					fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
							fileURL.length());
				}
				inputStream = httpConn.getInputStream();

			}
			return true;
		} catch (Exception ex) {
			return false;
		}

	}

	@Override
	protected Void doInBackground() throws Exception {
		success = downloadFile(downloadURL);
		outputStream = new FileOutputStream(saveDirectory);
		byte[] buffer = new byte[BUFFER_SIZE];
		int bytesRead = -1;
		long totalBytesRead = 0;
		int percentCompleted = 0;
		long fileSize = contentLength;
		while ((bytesRead = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytesRead);
			totalBytesRead += bytesRead;
		}
		outputStream.close();
		inputStream.close();
		httpConn.disconnect();
		finish = true;
		return null;
	}

	@Override
	protected void done() {
		success = (success & (!isCancelled()));
	}
}
